//问题模块
define('studioProblem', ['config', 'cookie', 'jquery', 'handlebars', 'showBigImg'], function(config, cookie, $, Handlebars, showBigImg){
	//定义hanlebars helper
	function helper(){
		//判断当前用户是否已对该问题点赞
		Handlebars.registerHelper('if_zan', function(value, options){
			if(value == 1){
				return options.fn(this);
			}
			else{
				return options.inverse(this);
			}
		});
		//判断头像是否为空
		Handlebars.registerHelper('if_empty', function(value, options){
			if(value == ''){
				return options.fn(this);
			}
			else{
				return options.inverse(this);
			}
		});
		//判断回答是老师还是画室
		Handlebars.registerHelper('if_studio', function(value, options){
			if(value == 2){
				return options.fn(this);
			}
			else{
				return options.inverse(this);
			}
		});
	}

	//处理服务器返回问题列表数据
	function process_data(data){
		//添加hasImage标记+处理时间戳
		for (var i = 0; i < data['problems'].length; i++) {
			if (data['problems'][i]['image'] != ''){
				data['problems'][i]['hasImage'] = true;
			}

			var publishTime = process_timestamp(data['problems'][i]['timestamp']);
			data['problems'][i]['publishTime'] = publishTime;
		}
		return data;
	}

	//时间戳处理
	function process_timestamp(data){
		var exp = new Date();
		exp.setTime(data);
		//把时间分开装入数组，对只有一位的值进行前补0处理
		var timeArray = [exp.getFullYear(), (exp.getMonth()+1), 
			exp.getDate(), exp.getHours(), exp.getMinutes(), exp.getSeconds()];
		for (var j = 0; j < 6; j++) {
			if (timeArray[j].toString().length == 1){
				timeArray[j] = '0' + timeArray[j];
			}
		}
		var publishTime = timeArray[0] + '.' + timeArray[1] + '.' + timeArray[2]
				+ '  ' + timeArray[3] + ':' + timeArray[4] + ':' + timeArray[5];

		return publishTime;
	}

	//调整头像高度（超过宽度时截去）
	function adjustAvatar(rowClassName){
		var colWidth = $(rowClassName + ':eq(0) img').width();
		$(rowClassName).css('height', colWidth +'px');

		//更改浏览器窗口大小时
		$(window).resize(function(){
			var colWidth = $(rowClassName + ':eq(0) img').width();
			$(rowClassName).css('height', colWidth + 'px');
		});
	}
	

	//返回函数列表
	return {
		getProblemList: function(skip, total, userId, callback,studioId){
			var request = $.ajax({
				url: config['api']['getStudioAnswers'][0].replace(/\<\w+\>/,studioId),
				type: config['api']['getStudioAnswers'][1],
				data: {
					skip: skip,
					total: total,
					userId: userId
				},
				dataType: 'json',
				async: true,
				error: function(err){
					console.log('get problem failed!');
				},
				success: function(data){
					//处理数据(添加publishTime, hasImage)
					data = process_data(data);
					console.log(data);
					//注册helper
					helper();
					//模板生成中心问题
					var source = $("#problems-template").html();
					var template = Handlebars.compile(source);
					//$('#problems').html($('.center-problem').html() + template(data));
					$('#problems').append(template(data));
					//点开大图模块
					$('.articles .paintings img').on('click', function(){
						var src = $(this).attr('src');
						showBigImg(src);
					});
					//调整中心问题区头像的高度为其宽度
					adjustAvatar('.left-col');

					//调用回调
					if (callback){
						callback(data['problems'].length);
					}
				}
			});
		},
		getProblemById: function(userId, problemId){
			//获取中心问题内容
			var problem_request = $.ajax({
				url: config['api']['getProblemById'][0].replace('<problem_id>', problemId),
				type: config['api']['getProblemById'][1],
				data: {
					userId: userId
				},
				dataType: 'json',
				async: true,
				error: function(err){
					console.log('get problem failed!');
				},
				success: function(data){
					//处理数据(添加publishTime, hasImage)
					if (data['problem']['image'] != ''){
						data['problem']['hasImage'] = true;
					}
					var publishTime = process_timestamp(data['problem']['timestamp']);
					data['problem']['publishTime'] = publishTime;

					for (var i = 0; i < data['problem']['commentList'].length; i++) {
						publishTime = process_timestamp(data['problem']['commentList'][i]['timestamp']);
						data['problem']['commentList'][i]['publishTime'] = publishTime;
					}
					for (var i = 0; i < data['problem']['answerList'].length; i++) {
						var updateTime_changed = process_timestamp(data['problem']['answerList'][i]['updateTime']);
						data['problem']['answerList'][i]['updateTime_changed'] = updateTime_changed;
						data['problem']['answerList'][i]['toUserId'] = data['problem']['userId'];
						data['problem']['answerList'][i]['toUserName'] = data['problem']['name'];
					}				

					console.log(data);
					//注册helper
					helper();
					//模板生成中心问题
					var source = $("#problems-template").html();
					var template = Handlebars.compile(source);
					$('.center-problem').html($('.center-problem').html() + template(data['problem']));

					//点开大图模块
					$('.articles .paintings img').on('click', function(){
						var src = $(this).attr('src');
						showBigImg(src);
					});
					//调整中心问题区头像的高度为其宽度
					adjustAvatar('.left-col');

					//模板生成问题评论
					if (data['problem']['commentList'].length > 0){		//评论数大于0
						source = $("#comments-template").html();
						template = Handlebars.compile(source);
						$('.main-comments').html($('.main-comments').html() + template(data['problem']['commentList']));

						//调整评论区头像的高度
						adjustAvatar('.comment-left-col');
					}
					else{	//暂无评论
						$('.information h2').css('display', 'block');
					}

					//模板生成问题回答
					if (data['problem']['answerList'].length > 0){		//评论数大于0
						source = $("#answers-template").html();
						template = Handlebars.compile(source);
						$('.main-comments').html($('.main-comments').html() + template(data['problem']['answerList']));

						//调整评论区头像的高度
						adjustAvatar('.comment-left-col');
					}
				}
			});
			
		},
		//对问题点赞或取消赞
		clickZan: function(){
			$(document).on('click', '.left-zan img', function(){
				var userId = cookie.getCookie('userId');
				if (userId != ''){		//已登录
					if ($(this).hasClass('active')){	//取消赞
						var zan = -1;
						$(this).removeClass('active');
						$(this).attr('src', 'image/clickZan.png');
						var $zan = $(this).parents('.left-zan').find('.num');
						var new_zan = parseInt($zan.text()) - 1;
						$zan.text(new_zan);
					}
					else{								//点赞
						var zan = 1;
						$(this).addClass('active');
						$(this).attr('src', 'image/clickZan_active.png');
						var $zan = $(this).parents('.left-zan').find('.num');
						var new_zan = parseInt($zan.text()) + 1;
						$zan.text(new_zan);
					}
					var problem_id = $(this).parents('.articles').attr('data-problemId');

					var request = $.ajax({
						url: config['api']['clickZan'][0].replace('<problem_id>', problem_id),
						type: config['api']['clickZan'][1],
						data: {
							userId: userId,
							zan: zan
						},
						dataType: 'json',
						async: true,
						err: function(err){
							console.log(err);
						}
					});
				}
				else{		//未登录
					//还原右上角登录图标
					$('#top_bar .user').css('display', 'none');
					$('#top_bar .log_reg').css('display', 'inline');
					//取消已点赞的显示
					$('.left-zan img').attr('src', 'image/clickZan.png').removeClass('active');
					alert('请先登录！');
				}
			});
		},
		//问题详情页发表新评论
		newComment: function(){
			$(document).on('click', '.show-comments .normal-comment button', function(){
				var userId = cookie.getCookie('userId');

				if (userId != ''){
					var content = $(this).parent().find('textarea').val();
					var problemId = $(this).parents('.articles').attr('data-problemId');
					if (content == ''){
						alert('内容不能为空！');
						return ;
					}
					//改变按钮为不可选状态
					$(this).addClass('disabled');

					var request = $.ajax({
						url: config['api']['postComment'][0].replace('<user_id>', userId),
						type: config['api']['postComment'][1],
						data: {
							content: content,
							problemId: problemId
						},
						dataType: 'json',
						async: true,
						error: function(err){
							console.log('comment failed!');
							alert('评论失败，请重试！')
							$('.show-comments .normal-comment button').removeClass('disabled');
						},
						success: function(data){
							alert('评论发表成功！');
							window.location.reload();
						}
					});
				}
				else{
					alert('请先登录！');
					$('#top_bar .user').css('display', 'none');
					$('#top_bar .log_reg').css('display', 'inline');	
					$('.user-info').css('display', 'none');
				}
			});
		},
		//回复评论
		replyComment: function(){
			//对某条评论按回复
			$(document).on('click', '.main-comments .comment-right-col span', function(){
				var fromUser = $(this).parents('.comment-content').attr('data-fromUser');
				var fromUserName = $(this).parents('.comment-right-col').find('h5 a').text();
				$('.information .normal-comment').css('display', 'none');
				$('.information .reply').css('display', 'block');
				$('.information .reply').attr('data-replyTo', fromUser);
				$('.information .reply textarea').attr('placeholder', '回复 @'+fromUserName+' : ')
			});
			//按取消
			$(document).on('click', '.show-comments .reply .reply-cancel', function(){
				$('.information .reply').css('display', 'none');
				$('.information .normal-comment').css('display', 'block');
			});
			//提交回复
			$(document).on('click', '.show-comments .reply .reply-submit', function(){
				var userId = cookie.getCookie('userId');

				if (userId != ''){
					var content = $(this).parent().find('textarea').val();
					var problemId = $(this).parents('.articles').attr('data-problemId');
					var replyTo = $(this).parent().attr('data-replyTo');
					if (content == ''){
						alert('内容不能为空！');
						return ;
					}
					//改变按钮为不可选状态
					$(this).addClass('disabled');

					var request = $.ajax({
						url: config['api']['postComment'][0].replace('<user_id>', userId),
						type: config['api']['postComment'][1],
						data: {
							replyTo: replyTo,
							content: content,
							problemId: problemId
						},
						dataType: 'json',
						async: true,
						error: function(err){
							console.log('comment failed!');
							alert('评论失败，请重试！')
							$('.show-comments .reply button').removeClass('disabled');
						},
						success: function(data){
							alert('评论发表成功！');
							window.location.reload();
						}
					});
				}
				else{
					alert('请先登录！');
					$('#top_bar .user').css('display', 'none');
					$('#top_bar .log_reg').css('display', 'inline');	
					$('.user-info').css('display', 'none');
				}
			});	
		}
	};
});
